console.log('redirect to login because users key did not validate properly on server end');
redirectTo('/login', { res: ctx.res, status: 301 });
}
return { ...pageProps };
}
}
static propTypes = {
token: PropTypes.string,
}
static defaultProps = {
token: '',
}
constructor(props, context) {
super(props, context);
this.state = {
loading: true,
account: {},
};
this.api = new Api(props.token);
this.context.setApi(this.api);
}
componentDidMount() {
const account = {
loggedIn: this.props.token != null && this.props.token !== '',
firstName: LocalStorage.getFirstName(),
lastName: LocalStorage.getLastName(),
email: LocalStorage.getEmail(),
role: LocalStorage.getRole() || 'unauthenticated',
id: LocalStorage.getId(),
};
if (!allowedRoles.includes(account.role)) {
console.log('redirect user to login if not authenticated, or redirect to home page because no access');
Router.push(account.role === 'unauthenticated' ? '/login' : '/');
return;
}
this.context.setAccount(account);
this.setState({ account, loading: false });
}
render() {
if (!this.state.loading) {
return (
<WrappedComponent
{...this.props}
account={this.state.account}
api={this.api}
/>
);
}
return null;
}
}
hoistNonReactStatics(withAuth, WrappedComponent, { getInitialProps: true });
withAuth.allowedRoles = allowedRoles;
withAuth.contextType = AuthContext;
withAuth.displayName = `withAuth(${WrappedComponent.displayName})`;
return withAuth;
};